package com.des1gn.service;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONArray;
import com.des1gn.common.bean.RetryErrorMqMessageDto;
import com.des1gn.processor.RetryFaultHandler;
import com.des1gn.processor.RetryFaultProcessor;
import com.des1gn.redis.ObjectRedisClient;
import com.rrtv.rpc.client.config.RpcClientProperties;
import com.rrtv.rpc.client.proxy.ClientStubProxyFactory;
import com.rrtv.rpc.core.discovery.DiscoveryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @ClassName RetryFaultProcess
 * @Description TODO
 * @Author Des1gn
 * @Version 1.0
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class RetryFaultProcess implements RetryFaultHandler {

    private final ObjectRedisClient objectRedisClient;

    private final RetryFaultProcessor retryFaultProcessor;

    private static final String RETRY_FAULT_CACHE = "retry.fault.data";

    private String generatorRetryFlaultKey(RetryErrorMqMessageDto messageDto){
        StringBuilder keyBuilder = new StringBuilder();
        keyBuilder.append(messageDto.getTargetClassName());
        keyBuilder.append(messageDto.getTargetMethodName());
        keyBuilder.append(JSONArray.toJSONString(messageDto.getTargetArgs()));
        return SecureUtil.md5(keyBuilder.toString());
    }

    @Override
    public void retryFaultProcess(RetryErrorMqMessageDto messageDto){
        String key = generatorRetryFlaultKey(messageDto);
        objectRedisClient.hPut(RETRY_FAULT_CACHE,key,messageDto);
    }

    public Map<Object, Object> getRetryFaultTaskList(){
        return objectRedisClient.hGetAll(RETRY_FAULT_CACHE);
    }

    public Boolean invokeRetryFaultTask(String id){
        RetryErrorMqMessageDto dto = (RetryErrorMqMessageDto)objectRedisClient.hGet(RETRY_FAULT_CACHE, id);
        return retryFaultProcessor.invokeRetryFaultTask(dto);
    }

}
